package com.sopaths.connect.qq;

import javax.inject.Named;
import javax.servlet.ServletRequest;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.sopaths.connect.ConnectAdapter;
import com.sopaths.contract.connect.OAuthToken;
import com.sopaths.contract.domain.LoginType;
import com.sopaths.contract.domain.User;
import com.sopaths.utility.web.WebUtil;

@Named("qqConnectAdapter")
public class QQConnectAdapter implements ConnectAdapter {
//	private Logger logger = Logger.getLogger(QQConnectAdapter.class);

	@Override
	public String getAuthorizeURL() {
		try {
			Oauth oauth = new Oauth();
			ServletRequest request = WebUtil.getRequest();
			String url = oauth.getAuthorizeURL(request);
			return url;
		} catch (IllegalStateException | QQConnectException ex) {
			throw new RuntimeException(ex);
		}
	}

	@Override
	public OAuthToken getToken() {
		try {
			Oauth oauth = new Oauth();
			ServletRequest request = WebUtil.getHttpServletRequest();
			AccessToken qqAccessToken = oauth.getAccessTokenByRequest(request);
			OAuthToken token = new OAuthToken();
			token.setAccessToken(qqAccessToken.getAccessToken());
			token.setExpiredIn(qqAccessToken.getExpireIn());

			OpenID openIDService = new OpenID(token.getAccessToken());
			String openID = openIDService.getUserOpenID();
			token.setOpenID(openID);

			return token;
		} catch (IllegalStateException | QQConnectException ex) {
			throw new RuntimeException(ex);
		}
	}

	@Override
	public User getUserInfo(OAuthToken token) {
		try {
			UserInfo userInfo = new UserInfo(token.getAccessToken(), token.getOpenID());
			UserInfoBean userInfoBean = userInfo.getUserInfo();

			User user = new User();
			user.setUsername(userInfoBean.getNickname());
			user.setLoginType(LoginType.QQ);
			user.setToken(token);
			return user;
		} catch (QQConnectException ex) {
			throw new RuntimeException(ex);
		}
	}

}
